package com.zhiyou.app.common.constant;

import cn.hutool.cache.impl.TimedCache;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zhiyou.app.common.starejob.StartJob;
import com.zhiyou.app.pojo.entity.TaskEntity;
import com.zhiyou.app.pojo.enums.TaskStatusEnum;
import com.zhiyou.app.service.ITaskService;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

@Component
public class OrderTaskCacheMapping implements StartJob {
    @Resource
    private ITaskService taskService;

    private static final TimedCache<String, String> ORDER_TASK_PID_MAPPING = new TimedCache<>(TimeUnit.DAYS.toMillis(1));

    @Override
    public void run() throws Exception {
        taskService.list(new LambdaQueryWrapper<TaskEntity>().ne(TaskEntity::getTaskStatus, TaskStatusEnum.COMPLETE).ne(TaskEntity::getTaskPid, null).ne(TaskEntity::getOrderNum, null)).forEach(k -> {
            ORDER_TASK_PID_MAPPING.put(k.getTaskPid(), k.getOrderNum());
        });
        ORDER_TASK_PID_MAPPING.schedulePrune(TimeUnit.DAYS.toMillis(3000));
    }

    public void putOrderNumByPid(String pId, String orderNum) {
        ORDER_TASK_PID_MAPPING.put(pId, orderNum);
    }

    public void removeByPid(String pId) {
        ORDER_TASK_PID_MAPPING.remove(pId);
    }

    public String getOrderNumByPid(String pId) {
        if (!ORDER_TASK_PID_MAPPING.containsKey(pId)) {
            taskService.list(new LambdaQueryWrapper<TaskEntity>().eq(TaskEntity::getTaskPid, pId)).stream().findFirst().ifPresent(k -> {
                ORDER_TASK_PID_MAPPING.put(pId, k.getOrderNum());
            });
        }
        return ORDER_TASK_PID_MAPPING.get(pId, true);
    }

}
